import json
import platform
from io import BytesIO

from django.shortcuts import render, HttpResponse, redirect

from App import models
from App.forms.add_info_form import AddInfoForm
from App.forms.add_order_form import AddOrderForm
from App.forms.case_form import CaseForm
from App.forms.company_form import CompanyForm
from App.forms.employee_form import EmployeeForm
from App.forms.hotel_form import HotelForm
from App.forms.index_form import IndexForm
from App.forms.login_form import LoginForm
from App.forms.order_creat_form import OrderCreatForm
from App.forms.question_form import QuestionCreatForm
from App.forms.register_form import RegisterForm
from App.global_var import *
from App.models import Company, Employee, Case, Hotel
from App.utils.my_tools import *

# 字典映射
contrast_dic = {
    '婚宴时间': 'marryTime',
    '订单编号': 'orderId',
    '员工编号': 'userId',
    '员工电话': 'phone',
    '客户姓名': 'customer',
    '联系电话': 'c_phone',
    '其他联系方式': 'c_other',
    '金额': 'prize',
    '订单状态': 'status',
    '备注': 'note',
}


# 获取验证码
def image_code(request):
    image_object, code_text = check_code()
    stream = BytesIO()
    image_object.save(stream, 'png')
    request.session['code'] = code_text
    return HttpResponse(stream.getvalue())


# 处理登录页面的GET请求
def login(request):
    if request.method == 'GET':
        login_form = LoginForm()
        return render(request, 'login.html', {'form': login_form})


# 此函数用来处理登录页的POST请求
def login_ajax(request):
    login_form = LoginForm(request.POST)  # 通过请求数据实例化对象
    # 获取转入login前的地址
    target_url = request.GET.get('next')
    username = request.POST.get('username')
    user = User.objects.filter(username=username).last()
    set_global_code(request.session.get('code'))
    # 如果数据满足验证
    if login_form.is_valid():
        # 设置session的key and value
        user_id = user.userId
        admin_type = user.admin_type
        # 用户名会有特殊字符可能会导致出现重复的情况，所以改用id记录对应信息。
        request.session['userId'] = user_id
        request.session['admin_type'] = admin_type
        # 设置session的消亡时间为用户关闭页面时
        request.session.set_expiry(0)
        # 判断是否从其它地址跳转至login页
        if target_url:
            redirect_url = target_url
        else:
            redirect_url = '/index/'
        data_dict = {
            'status': True,
            'redirect_url': redirect_url,
        }
        data_json = json.dumps(data_dict)  # 成功后即可返回状态位True
        return HttpResponse(data_json)
    # 如果数据不满足验证
    errors = login_form.errors  # 此处错误字典会自动保存上方验证失败后的错误提示
    data_dict = {
        'status': False,
        'errors': errors,  # 生成字典，携带错误信息
    }
    data_json = json.dumps(data_dict)
    return HttpResponse(data_json)  # 返回前端渲染


# 处理注册页面的GET请求
def register(request):
    if request.method == 'GET':
        form = RegisterForm()  # 实例化对象，其中每个field in form都是一个input框
        return render(request, 'register.html', {'form': form})  # 返回到前端渲染


# 此函数用来处理注册页的POST请求
def register_ajax(request):
    register_form = RegisterForm(request.POST)  # 通过请求数据实例化对象
    username = request.POST.get('username')
    # 获取是否勾选root权限
    super_user = request.POST.get('super-user')
    user = User.objects.filter(username=username)
    if register_form.is_valid():
        register_form.save()
        if super_user == 'on':
            user.update(admin_type='administrator')
        else:
            user.update(admin_type='ordinary')
        user_id = user.last().userId
        admin_type = user.last().admin_type
        # 由于注册后补全信息后直接进入index页面，所以此处将注册成功用户userId记录到session
        request.session['userId'] = user_id
        request.session['admin_type'] = admin_type
        request.session.set_expiry(0)
        data_dict = {
            'status': True
        }
        data_json = json.dumps(data_dict)
        return HttpResponse(data_json)
    # 如果数据不满足验证
    errors = register_form.errors  # 此处错误字典会自动保存上方验证失败后的错误提示
    data_dict = {
        'status': False,
        'errors': errors,  # 生成字典，携带错误信息
    }
    data_json = json.dumps(data_dict)
    return HttpResponse(data_json)  # 返回前端渲染


# 主页
def index(request):
    # 获取当前登录用户的userId
    user_id = request.session.get('userId')
    user = User.objects.filter(userId=user_id).first()
    staff = User.objects.filter().all()
    staff_count = staff.count()
    case = Case.objects.first()
    index_dic, view_url, company_info, company_status = index_txt_read()
    # 获取用户头像地址
    img_obj = user.headImg
    nickname = user.name
    return render(request, 'index.html', {
        'case': case,
        'img': img_obj,
        'nickname': nickname,
        'staff': staff,
        'staff_count': staff_count,
        'index_dic': index_dic,
        'view_url': view_url,
        'company_info': company_info,
        'company_status': company_status,
    })


# 退出登录
def logout(request):
    request.session.flush()
    return redirect('/')


# 补全个人信息页面
def add_info(request):
    if request.method == 'GET':
        user_id = request.session.get('userId')
        user = User.objects.filter(userId=user_id).first()
        password = user.password
        form = AddInfoForm(initial={'password': password})
        user_type_from_db = user.admin_type
        user_type = judge_admin_type(user_type_from_db)
        return render(request, 'addInfo.html', {'form': form, 'user_type': user_type})


# 信息补全页面Ajax
def add_info_ajax(request):
    user_id = request.session['userId']
    user = User.objects.filter(userId=user_id)
    addinfo_form = AddInfoForm(request.POST, request.FILES)
    if addinfo_form.is_valid():
        # 处理上传的图片
        file = request.FILES.get('headImg')
        if file is not None:
            img_name = file.name  # 获取图片名称
            upload_handle(file, img_name, user_id, 'users')
        user.update(name=addinfo_form.clean_name(),
                    phone=addinfo_form.clean_phone(),
                    position=addinfo_form.clean_position(),
                    password=addinfo_form.clean_password())
        user_img_url = user.first().headImg.url
        data_dict = {
            'status': True,
            'user_img_url': user_img_url
        }
        data_json = json.dumps(data_dict)
        return HttpResponse(data_json)
    # 如果数据不满足验证
    errors = addinfo_form.errors
    data_dict = {
        'status': False,
        'errors': errors,
    }
    data_json = json.dumps(data_dict)
    return HttpResponse(data_json)


# 后台界面
def personal(request):
    # 获取当前登录用户的userId
    user_id = request.session.get('userId')
    user = User.objects.filter(userId=user_id).first()
    img_obj = user.headImg
    nickname = user.name
    position = user.position
    user_type = judge_admin_type(user.admin_type)

    if request.method == 'GET':
        # 日历简报
        surplus_task, follow_task = calendar_mask(user_id)
        # 销售简报
        sales_chance, signed_count, signed_amount, need_allocated = sales_kit(user_id)
        # 已完成订单
        executed_orders, executed_order_amount, denominator = order_completed(user_id)
        # 未完成订单
        this_month, next_month = order_incomplete(user_id)
        # # 消息记录
        # show_detail = message_record(user_id, str_now_time)
        # 已完成任务
        completed_detail = task_completed(user_id, str_now_time)
        # 已完成任务
        incomplete_detail = task_incomplete(user_id, str_now_time)

        result = {
            'img_url': img_obj.url,  # 头像地址
            'nickname': nickname,  # 昵称
            'position': position,  # 职位
            'user_type': user_type,  # 用户权限

            'calendar_mask': {
                'surplus_task': surplus_task,  # 剩余任务数量
                # 'dialog_count': dialog_count,  # 今日沟通记录数量
                'follow_task': follow_task,  # 跟进项
            },
            'sales_kit': {
                'sales_chance': sales_chance,  # 销售机会
                'signed_count': signed_count,  # 签单量
                'signed_amount': signed_amount,  # 签单额
                'need_allocated': need_allocated,  # 待分配
            },
            'order_completed': {
                'executed_orders': executed_orders,  # 已执行订单
                'executed_order_amount': executed_order_amount,  # 执行订单额
                'independent_sign_ratio': str(signed_count) + ':' + str(denominator),  # 自主签单比
            },
            'order_incomplete': {
                'this_month': this_month,  # 本月未完成订单
                'next_month': next_month,  # 下月未完成订单
            },
            # 'message_record': {
            #     'show_detail': show_detail,  # 我的消息记录
            # },
            'task_completed': {
                'detail': completed_detail,  # 已完成任务
            },
            'task_incomplete': {
                'detail': incomplete_detail,  # 未完成任务
            },
        }
        return render(request, 'personal.html', {'result': result})


# 更新个人信息页面
def update_info(request):
    user_id = request.session.get('userId')
    user_all = User.objects.exclude(userId=user_id)
    user = User.objects.filter(userId=user_id).first()
    img_obj = user.headImg
    nickname = user.name
    position = user.position
    username = user.username
    password = user.password
    user_type = judge_admin_type(user.admin_type)
    phone = user.phone
    form = AddInfoForm(instance=user)
    user_all_count = user_all.count()
    page_size = 7
    page_step = 2
    page_current = int(request.GET.get('page', 1))
    div, user_info, page_list = pagination(user_all_count, user_all, page_size, page_step, page_current)
    result = {
        'img_url': img_obj.url,
        'nickname': nickname,
        'position': position,
        'username': username,
        'password': password,
        'user_type': user_type,
        'phone': phone,
        'div': div,
        'user_info': user_info,
        'page_list': page_list
    }
    return render(request, 'updateInfo.html', {
        'form': form,
        'result': result,
    })


# 删除用户的ajax请求
def delete_user_info_ajax(request):
    delete_flag = True
    msg = '删除成功！'
    try:
        wait_delete_id = request.POST.get('userId')
        wait_delete_url = User.objects.filter(userId=wait_delete_id).first().headImg
        if wait_delete_url != 'users/default.png':
            os.remove('%s/%s' % (settings.MEDIA_ROOT, wait_delete_url))
        User.objects.filter(userId=wait_delete_id).delete()
    except all as e:
        print(repr(e))
        delete_flag = False
    data_dict = {
        'status': delete_flag,
        'msg': msg
    }
    data_json = json.dumps(data_dict)
    return HttpResponse(data_json)


# 是否完成任务Ajax
def whether_complete_ajax(request):
    user_id = request.session.get('userId')
    year_month = request.POST.get('yearmonth')
    completed_detail = task_completed(user_id, year_month)
    incomplete_detail = task_incomplete(user_id, year_month)

    data_dict = {
        'status': True,
        'task_completed': completed_detail,
        'task_incomplete': incomplete_detail,
    }
    data_json = json.dumps(data_dict)
    return HttpResponse(data_json)


# # 点击日期更新消息记录Ajax
# def select_day_ajax(request):
#     user_id = request.session.get('userId')
#     # year_month_day = request.POST.get('year_month_day')
#     user = User.objects.filter(userId=user_id).first()
#     nick_name = user.name
#     user_img_url = user.headImg.url
#     show_detail = message_record(user_id)
#
#     data_dict = {
#         'status': True,
#         'nickname': nick_name,
#         'user_img_url': '/static' + user_img_url,
#         'message_record': show_detail,
#     }
#     data_json = json.dumps(data_dict)
#     return HttpResponse(data_json)


# 图表数据交互Ajax
def charts_ajax(request):
    user_id = request.session.get('userId')
    month_order_count, total_profit = chart_data_process(user_id)

    data_dict = {
        'status': True,
        'month_order_count': month_order_count,
        'total_profit': total_profit,
    }
    data_json = json.dumps(data_dict)
    return HttpResponse(data_json)


# 创建订单管理Ajax
def order_manager_create_ajax(request):
    add_order_form = AddOrderForm(request.POST)
    user_id = request.session.get('userId')
    if add_order_form.is_valid():
        add_order_form.save()
        order = Order()
        order_id = OrderManager.objects.last().orderId
        order.orderId_id = order_id
        order.userId_id = user_id
        order.marryTime = OrderManager.objects.last().marryTime
        order.save()
        all_message = AllMessageM()
        all_message.orderId_id = order_id
        all_message.userId_id = user_id
        all_message.detail = order.type
        all_message.status = OrderManager.objects.last().status
        all_message.save()
        data_dict = {
            'status': True
        }
        data_json = json.dumps(data_dict)
        return HttpResponse(data_json)
    errors = add_order_form.errors
    data_dict = {
        'status': False,
        'errors': errors,
    }
    data_json = json.dumps(data_dict)
    return HttpResponse(data_json)


# 个人订单
def personal_order(request):
    set_global_url(request.get_full_path())
    # 获取查询状态
    page_flag = get_global_flag()
    if page_flag != 'perpage':  # 此处的if语句用于解决查询条件混乱的情况
        set_global_flag(None)
        page_flag = get_global_flag()
    # 页面基本信息
    user_id = request.session.get('userId')
    user = User.objects.filter(userId=user_id).first()
    img_obj = user.headImg
    nickname = user.name
    position = user.position
    user_type = judge_admin_type(user.admin_type)
    form = AddOrderForm(initial={'userId': user_id})  # 订单添加表单

    if page_flag is None:  # 不在查询状态
        order_manager_origin = OrderManager.objects.filter(userId=user_id).all().order_by('-marryTime')

    else:
        wait_query_key = get_global_key()  # 查询关键字
        wait_query_value = get_global_value()  # 查询值
        dic = {contrast_dic[wait_query_key] + '__contains': wait_query_value,
               'userId': user_id, }
        order_manager_origin = OrderManager.objects.filter(**dic).order_by('-marryTime')

    page_size = 10  # 单页容量
    page_step = 2  # 页码步长
    page_current = int(request.GET.get('page', 1))  # 当前页码
    order_manager_count = order_manager_origin.count()  # 数据总量
    div, order_manager, page_list = pagination(order_manager_count, order_manager_origin, page_size,
                                               page_step, page_current)
    result = {
        'div': div,
        'order_manager': order_manager,
        'img_url': img_obj.url,
        'nickname': nickname,
        'position': position,
        'page_list': page_list,
        'user_type': user_type,
        'page_flag': page_flag
    }
    return render(request, 'personalPerOrder.html', {'result': result, 'form': form})


# 全部订单
def all_order(request):
    set_global_url(request.get_full_path())
    page_flag = get_global_flag()
    if page_flag != 'allpage':
        set_global_flag(None)
        page_flag = get_global_flag()
    user_id = request.session.get('userId')
    form = AddOrderForm(initial={'userId': user_id})
    user = User.objects.filter(userId=user_id).first()
    img_obj = user.headImg
    nickname = user.name
    position = user.position
    user_type = judge_admin_type(user.admin_type)
    if page_flag is None:  # 不在查询状态
        order_manager_origin = OrderManager.objects.filter(userId=user_id).all().order_by('-marryTime')
    else:
        wait_query_key = get_global_key()  # 查询关键字
        wait_query_value = get_global_value()  # 查询值
        if wait_query_key == '员工编号':
            dic = {contrast_dic[wait_query_key]: wait_query_value}
        else:
            dic = {contrast_dic[wait_query_key] + '__contains': wait_query_value}
        order_manager_origin = OrderManager.objects.filter(**dic).order_by('-marryTime')
    page_size = 10  # 单页容量
    page_step = 2  # 页码步长
    page_current = int(request.GET.get('page', 1))  # 当前页码
    order_manager_count = order_manager_origin.count()  # 数据总量
    div, order_manager, page_list = pagination(order_manager_count, order_manager_origin, page_size,
                                               page_step, page_current)
    result = {
        'div': div,
        'order_manager': order_manager,
        'page_list': page_list,
        'img_url': img_obj.url,
        'nickname': nickname,
        'position': position,
        'user_type': user_type,
        'page_flag': page_flag
    }
    if user_type == '管理员':
        return render(request, 'personalAllOrder.html', {'result': result, 'form': form})
    else:
        return HttpResponse('禁止访问')


# 搜索结果
def search_result(request):
    # 开始查询
    if request.GET.get('flag') is not None:
        set_global_flag(request.GET.get('flag'))  # 设置查询关键字
        set_global_key(request.GET.get('key'))  # 设置查询键
        set_global_value(request.GET.get('value'))  # 设置查询值
    else:
        # 恢复初始状态
        set_global_flag(None)
        set_global_key(None)
        set_global_value(None)
    return HttpResponse(json.dumps({'status': True}))


# 订单管理修改
def order_manager_update_ajax(request):
    order_id = request.POST.get('orderId')
    order_manager = OrderManager.objects.filter(orderId=order_id).first()
    all_message = AllMessageM.objects.filter(orderId=order_id).first()
    add_order_info = AddOrderForm(request.POST, instance=order_manager)
    # print(request.POST)
    if add_order_info.is_valid():
        add_order_info.save()
        marry_time = order_manager.marryTime
        Order.objects.filter(orderId=order_id).update(marryTime=marry_time)
        all_message.status = add_order_info.cleaned_data.get("status")
        all_message.save()
        data_dict = {
            'status': True
        }
        data_json = json.dumps(data_dict)
        return HttpResponse(data_json)

    errors = add_order_info.errors
    data_dict = {
        'status': False,
        'errors': errors,
    }
    data_json = json.dumps(data_dict)
    return HttpResponse(data_json)


# 订单详情修改
def order_details_update(request, order_id):
    order_manager = OrderManager.objects.filter(orderId=order_id)
    order = Order.objects.filter(orderId=order_id).first()
    all_message = AllMessageM.objects.filter(orderId=order_id).first()
    user_id = request.session.get('userId')
    show_detail = message_record(order_id)
    user = User.objects.filter(userId=user_id).first()
    user_type = judge_admin_type(user.admin_type)
    img_obj = user.headImg
    nickname = user.name
    position = user.position
    url = get_global_url()
    form = OrderCreatForm(instance=order, initial={'userId': user_id, 'orderId': order_id})
    if request.method == "POST":
        form = OrderCreatForm(request.POST, instance=order, initial={'userId': user_id, 'orderId': order_id})
        if form.is_valid():
            form.save()
            marry_time = form.cleaned_data['marryTime']
            order_manager.update(marryTime=marry_time)
            all_message.detail = form.cleaned_data.get("type")
            all_message.save()
            return redirect(url)

    result = {
        'img_url': img_obj.url,
        'nickname': nickname,
        'position': position,
        'user_type': user_type,
        'current_url': url,
        'show_detail': show_detail,
    }
    return render(request, 'orderDetails.html', {'form': form, 'result': result})


# 消息记录Ajax
def message_record_ajax(request):
    user_id = request.session.get('userId')
    user_img_url = User.objects.filter(userId=user_id).first().headImg.url
    order_id = request.POST.get('orderId')
    expect_time = request.POST.get('task_time')
    detail = request.POST.get('task_info')
    # 正则规范化用户输入信息只允许数字、字母、中文汉字并以空格为分界
    format_detail = re.sub('([^\u4e00-\u9fa5\u0030-\u0039\u0041-\u007a])', ' ', detail)
    # 获取MyMessageM表内userId名下expect_time为添加的时间的QuerySet
    time_message = MyMessageM.objects.filter(orderId=order_id, expect_time=expect_time)
    # 判断数据库内是否存在expect_time的数据
    if str(time_message) == '<QuerySet []>':
        task = MyMessageM()
        task.orderId_id = order_id
        task.detail = format_detail.strip()
        task.expect_time = expect_time
        task.status = '未完成'
        task.save()
    else:
        database_detail = time_message.values('detail')[0]['detail']
        # 判断用户输入的数据是否已存在，存在则pass否则加在原数据后
        if format_detail not in database_detail:
            new_detail = database_detail + ';' + format_detail
            time_message.update(detail=new_detail)

    data_dict = {
        'status': True,
        'user_img_url': '/static' + user_img_url,
    }
    data_json = json.dumps(data_dict)
    return HttpResponse(data_json)


# 删除消息的ajax
def delete_message_info_ajax(request):
    delete_flag = True
    msg = '删除成功！'
    try:
        wait_delete_id = request.POST.get('orderId')
        wait_delete_time = request.POST.get('expect_time')
        MyMessageM.objects.filter(orderId=wait_delete_id, expect_time=wait_delete_time).delete()
    except all:
        delete_flag = False
    data_dict = {
        'status': delete_flag,
        'msg': msg
    }
    data_json = json.dumps(data_dict)
    return HttpResponse(data_json)


# 婚嫁资源——婚庆公司展示
def marriage_resources_company(request):
    # 获取当前登录用户的userId
    user_id = request.session.get('userId')
    user = User.objects.filter(userId=user_id).first()
    user_type = judge_admin_type(user.admin_type)
    case = Case.objects.first()
    # 获取婚庆公司所有信息
    company = Company.objects.all()
    # 获取用户头像地址
    img_obj = user.headImg
    nickname = user.name.upper()
    company_total_count = len(company)  # 数据集长度
    col_company = 5  # 列数
    company_img_index = divide_rows(company_total_count, col_company, company)  # 调用分行函数
    # 获取婚庆公司首页图片 // 目前我想到了两种解决方案，第一种是数据库加一列，分为主页图片和内容多图，但在详情页可能也会遇到这个问题
    # 第二种是集合，切片后取第一张作为首页照片，然后返回给前端，问题出在我输出了第一张照片后，怎么传给前端的问题
    company_img_index = None if company_img_index == [[]] else company_img_index  # 如果列表为空则直接返回None
    return render(request, 'indexMarryRes.html', {
        'case': case,
        'img': img_obj,
        'nickname': nickname,
        'company': company_img_index,
        'user_type': user_type
    })


# 婚嫁资源——外聘表列表展示
def marriage_resources_types(request, types):
    # 获取当前登录用户的userId
    user_id = request.session.get('userId')
    user = User.objects.filter(userId=user_id).first()
    user_type = judge_admin_type(user.admin_type)
    case = Case.objects.first()

    # 获取不同雇员类型的信息
    employee_types = models.Employee.objects.filter(type_employee=types).all()
    employee_obj_index = divide_rows(len(employee_types), 5, employee_types)
    # 获取用户头像地址
    img_obj = user.headImg
    nickname = user.name.upper()
    employee_obj_index = None if employee_obj_index == [[]] else employee_obj_index  # 如果列表为空则直接返回None

    return render(request, 'indexEmployeeRes.html', {
        'case': case,
        'img': img_obj,
        'nickname': nickname,
        'employee_obj_index': employee_obj_index,
        'types': types,
        'user_type': user_type
    })


# 婚嫁资源——婚庆公司的详情页
def marriage_resources_company_detail(request, company_id):
    # 获取当前登录用户的userId
    user_id = request.session.get('userId')
    user = User.objects.filter(userId=user_id).first()
    case = Case.objects.first()
    # 获取当前婚庆公司的信息
    company_detail = models.Company.objects.filter(companyId=company_id).first()
    # 获取用户头像地址
    img_obj = user.headImg
    nickname = user.name.upper()
    # 获取婚庆公司相关数据
    company_name = company_detail.name_company
    info_company = company_detail.info_company
    img = company_detail.img_company
    index_img = company_detail.img_index
    video = company_detail.video_company
    images_list = str(img).split(' ')  # 将图片以空格形式分割开，列表存储
    img_url = '/media/companyRes/'  # 用于拼接的图片路径
    img_list = []  # 定义一个空列表，可以进行更新，用于存放最终的图片（路径+图片）
    for i in images_list:
        images = img_url + i  # 路径和图片进行拼接
        img_list.append(images)  # 更新列表
    img_list_divide = divide_rows(len(img_list), 5, img_list)
    result = {
        'img_index': index_img.url,
        'name': company_name,
        'info': info_company,
        'img_list': img_list_divide,
        'video': video
    }

    return render(request, 'indexMarryResDetails.html',
                  {'result': result, 'img': img_obj, 'nickname': nickname, 'case': case})


# 婚嫁资源——外聘表详情
def marriage_resources_types_detail(request, employee_id):
    # 获取当前登录用户的userId
    user_id = request.session.get('userId')
    user = User.objects.filter(userId=user_id).first()
    case = Case.objects.first()
    # 获取当前外聘表信息
    employee_detail = models.Employee.objects.filter(employeeId=employee_id).first()
    # 获取用户头像地址
    img_obj = user.headImg
    nickname = user.name.upper()
    # 获取外聘表详细信息
    employee_img_index = employee_detail.img_index
    employee_name = employee_detail.name_employee
    synopsis = employee_detail.note_employee
    img = employee_detail.img_employee
    video = employee_detail.video_employee
    images_list = str(img).split(' ')  # 将图片以空格形式分割开，列表存储
    img_url = '/media/employeeRes/'  # 用于拼接的图片路径
    img_list = []  # 定义一个空列表，可以进行更新，用于存放最终的图片（路径+图片）
    for i in images_list:
        images = img_url + i  # 路径和图片进行拼接
        img_list.append(images)  # 更新列表
    img_list = divide_rows(len(img_list), 5, img_list)
    video = video or None
    result = {
        'name': employee_name,
        'info': synopsis,
        'img_list': img_list,
        'img_index': employee_img_index.url,
        'video': video
    }
    return render(request, 'indexMarryResDetails.html',
                  {'result': result, 'img': img_obj, 'nickname': nickname, 'case': case})


# 资源上传页面
def resource_upload(request):
    company_total_count = Company.objects.count()
    employee_total_count = Employee.objects.count()
    case_total_count = Case.objects.count()
    hotel_total_count = Hotel.objects.count()
    company_form = CompanyForm()
    employee_form = EmployeeForm()
    case_form = CaseForm()
    hotel_form = HotelForm()
    index_form = IndexForm()
    user_id = request.session.get('userId')
    user = User.objects.filter(userId=user_id).first()
    img_obj = user.headImg
    nickname = user.name
    position = user.position
    user_type = judge_admin_type(user.admin_type)
    result = {
        'img_url': img_obj.url,
        'nickname': nickname,
        'position': position,
        'user_type': user_type,
        'company_total_count': company_total_count,
        'employee_total_count': employee_total_count,
        'case_total_count': case_total_count,
        'hotel_total_count': hotel_total_count
    }
    return render(request, 'uploadResource.html',
                  {'company_form': company_form, 'employee_form': employee_form, 'case_form': case_form,
                   'hotel_form': hotel_form, 'index_form': index_form,
                   'result': result})


# 婚庆公司资源上传的ajax请求
def company_info_ajax(request):
    company_form = CompanyForm(request.POST, request.FILES)
    if len(request.FILES) == 3:
        name = str(Company.objects.last().companyId + 1) if Company.objects.last() is not None else '1'
        index_url = request.FILES.get('img_index').name
        video_name = request.FILES.get('video_company').name
        request.FILES.get('img_index').name = get_new_name((name + '-index'), index_url)
        request.FILES.get('video_company').name = get_new_name((name + '-video'), video_name)
        company_form = CompanyForm(request.POST, request.FILES)
        img_name = []
        images = request.FILES.getlist('img_company')
        for i in images:
            img_name.append(i.name)
        if company_form.is_valid():
            company_form.save()

            upload_mul_handle(images, img_name, 'companyRes', Company)
            data_dict = {
                'status': True
            }
            data_json = json.dumps(data_dict)
            return HttpResponse(data_json)
    errors = company_form.errors
    data_dict = {
        'status': False,
        'errors': errors,
    }
    data_json = json.dumps(data_dict)
    return HttpResponse(data_json)


# 外聘表的资源上传ajax请求
def employee_info_ajax(request):
    employee_form = EmployeeForm(request.POST, request.FILES)
    is_upload = request.FILES.get('img_index') and request.FILES.get('img_employee')
    # if len(request.FILES) == 3:
    if is_upload:
        name = str(Employee.objects.last().employeeId + 1) if Employee.objects.last() is not None else '1'
        index_url = request.FILES.get('img_index').name
        if request.FILES.get('video_employee'):
            video_name = request.FILES.get('video_employee').name
            request.FILES.get('video_employee').name = get_new_name((name + '-video'), video_name)
        request.FILES.get('img_index').name = get_new_name((name + '-index'), index_url)
        employee_form = EmployeeForm(request.POST, request.FILES)
        img_name = []
        images = request.FILES.getlist('img_employee')
        for i in images:
            img_name.append(i.name)
        if employee_form.is_valid():
            employee_form.save()
            upload_mul_handle(images, img_name, 'employeeRes', Employee)
            data_dict = {
                'status': True
            }
            data_json = json.dumps(data_dict)
            return HttpResponse(data_json)
    errors = employee_form.errors
    data_dict = {
        'status': False,
        'errors': errors,
    }
    data_json = json.dumps(data_dict)
    return HttpResponse(data_json)


# 优秀案例资源上传的ajax请求
def case_info_ajax(request):
    case_form = CaseForm(request.POST, request.FILES)
    img_name = []
    images = request.FILES.getlist('img_case')
    for i in images:
        img_name.append(i.name)
    if case_form.is_valid():
        case_form.save()
        upload_mul_handle(images, img_name, 'caseRes', Case)
        data_dict = {
            'status': True
        }
        data_json = json.dumps(data_dict)
        return HttpResponse(data_json)
    errors = case_form.errors
    data_dict = {
        'status': False,
        'errors': errors,
    }
    data_json = json.dumps(data_dict)
    return HttpResponse(data_json)


# 酒店的资源上传的ajax请求
def hotel_info_ajax(request):
    hotel_form = HotelForm(request.POST, request.FILES)
    if len(request.FILES) == 2:
        name = str(Hotel.objects.last().hotelId + 1) if Hotel.objects.last() is not None else '1'
        index_url = request.FILES.get('img_index').name
        ppt_name = request.FILES.get('ppt').name
        request.FILES.get('img_index').name = get_new_name((name + '-index'), index_url)
        request.FILES.get('ppt').name = get_new_name((name + '-ppt'), ppt_name)
        hotel_form = HotelForm(request.POST, request.FILES)
        if hotel_form.is_valid():
            hotel_form.save()
            if platform.system().lower() == 'windows':
                convert_files_in_win(request.FILES.get('ppt').name)
            # elif platform.system().lower() == 'linux':
            #     convert_files_in_linux(request.FILES.get('ppt').name)
            hotel = Hotel.objects.last()
            wait_delete_url = str(hotel.ppt)
            os.remove('%s/%s' % (settings.MEDIA_ROOT, wait_delete_url))
            hotel.ppt = wait_delete_url.split('/')[0] + '/' + wait_delete_url.split('/')[1].split('.')[0] + '.pdf'
            hotel.save()
            data_dict = {
                'status': True
            }
            data_json = json.dumps(data_dict)
            return HttpResponse(data_json)

    errors = hotel_form.errors
    print(errors)
    data_dict = {
        'status': False,
        'errors': errors,
    }
    data_json = json.dumps(data_dict)
    return HttpResponse(data_json)


# 主页上传的ajax请求
def index_upload_ajax(request):
    index_form = IndexForm(request.POST, request.FILES)
    if index_form.is_valid():
        index_txt_write(request)
        data_dict = {
            'status': True,
        }
        data_json = json.dumps(data_dict)
        return HttpResponse(data_json)

    errors = index_form.errors
    data_dict = {
        'status': False,
        'errors': errors,
    }
    data_json = json.dumps(data_dict)
    return HttpResponse(data_json)


# 删除的ajax请求
def delete_res_ajax(request):
    delete_flag = True
    msg = '删除成功！请手动刷新页面！'
    try:
        real_name = request.POST.get('name_Id')
        wait_delete_id = int(request.POST.get('real_Id'))
        if real_name == 'companyId':
            delete_resource({real_name: wait_delete_id}, Company, 'companyRes')
        elif real_name == 'employeeId':
            delete_resource({real_name: wait_delete_id}, Employee, 'employeeRes')
        elif real_name == 'caseId':
            delete_resource({real_name: wait_delete_id}, Case, 'caseRes')
        elif real_name == 'hotelId':
            delete_resource({real_name: wait_delete_id}, Hotel, 'hotelRes')
    except Exception as e:
        print(repr(e))
        delete_flag = False
    data_dict = {
        'status': delete_flag,
        'msg': msg
    }
    data_json = json.dumps(data_dict)
    return HttpResponse(data_json)


# 优秀案例
def excellent_case(request, case_id):
    # 获取当前登录用户的userId
    user_id = request.session.get('userId')
    user = User.objects.filter(userId=user_id).first()
    # 获取用户头像地址
    img_obj = user.headImg
    nickname = user.name.upper()
    case_info = models.Case.objects.filter(caseId=case_id).first()
    case_name = []  # 创建一个空列表用于存放案例名
    case_indexes = []  # 创建一个空列表用于存放索引
    case = models.Case.objects.filter().all()
    for obj in case:
        case_name.append(obj.name_case)
        case_indexes.append(obj.caseId)
    case_zip = dict(zip(case_name, case_indexes))
    case_images = case_info.img_case
    images_list = str(case_images).split(' ')  # 将图片以空格形式分割开，列表存储
    img_url = '/media/caseRes/'  # 用于拼接的图片路径
    img_list = []  # 定义一个空列表，可以进行更新，用于存放最终的图片（路径+图片）
    for i in images_list:
        images = img_url + i  # 路径和图片进行拼接
        img_list.append(images)  # 更新列表
    case_img_count = len(img_list)
    result = {
        'case_img_count': case_img_count,
        'case_obj': case_info,
        'case_zip': case_zip,
        'img_list': img_list,
        'case_note': case_info.note_case
    }
    print(result)
    return render(request, 'indexExcellentCase.html',
                  {'result': result, 'img': img_obj, 'nickname': nickname})


# 酒店详情
def hotel_details(request):
    # 获取当前登录用户的userId
    user_id = request.session.get('userId')
    user = User.objects.filter(userId=user_id).first()
    hotel = models.Hotel.objects.filter().all()
    case = Case.objects.first()
    # 获取用户头像地址
    img_obj = user.headImg
    nickname = user.name.upper()
    hotel_total_count = len(hotel)  # 数据集长度
    col_hotel = 5  # 列数
    hotel_img_index = divide_rows(hotel_total_count, col_hotel, hotel)  # 调用分行函数
    # 返回前端hotelId字符串
    hotel_id = 'hotelId'
    hotel_img_index = None if hotel_img_index == [[]] else hotel_img_index
    return render(request, 'indexHotel.html', {
        'case': case,
        'img': img_obj,
        'nickname': nickname,
        'company_img_index': hotel_img_index,
        'hotel_id': hotel_id
    })


# 问题反馈提交ajax
def question_upload_ajax(request):
    data = {
        'question': request.POST.get('bug_error'),
        'username': User.objects.filter(userId=request.session.get('userId')).first().name
    }
    add_question_form = QuestionCreatForm(data)
    if add_question_form.is_valid():
        add_question_form.save()
        send_email(add_question_form.cleaned_data.get('question'))
        data_dict = {
            'status': True
        }
        data_json = json.dumps(data_dict)
        return HttpResponse(data_json)
    errors = add_question_form.errors
    data_dict = {
        'status': False,
        'errors': errors,
    }
    data_json = json.dumps(data_dict)
    return HttpResponse(data_json)


# 问题列表展示
def question_exhibition(request):
    user_id = request.session.get('userId')
    user = User.objects.filter(userId=user_id).first()
    # 获取用户信息
    user_type = judge_admin_type(user.admin_type)
    nickname = user.name.upper()
    position = user.position
    img_obj = user.headImg
    question_count = models.QuestionSubmission.objects.count()  # 获取数据总量
    page_size = 5  # 一页容量
    page_step = 2  # 页码步长
    page_current = int(request.GET.get('page', 1))  # 当前页
    question_origin = models.QuestionSubmission.objects.all().order_by('-questionId')

    div, question, page_list = pagination(question_count, question_origin, page_size,
                                          page_step, page_current)
    result = {
        'user_type': user_type,
        'nickname': nickname,
        'position': position,
        'img_url': img_obj.url,
    }
    return render(request, 'reportBug.html', {
        'div': div,
        'question': question,
        'page_list': page_list,
        'result': result
    })


# 删除订单Ajax
def delete_order_ajax(request):
    delete_flag = True
    msg = '删除成功！'
    try:
        wait_delete_id = request.POST.get('orderId')
        print(wait_delete_id)
        OrderManager.objects.filter(orderId=wait_delete_id).delete()
    except Exception as e:
        print(repr(e))
        delete_flag = False
        msg = "删除失败！"
    data_dict = {
        'status': delete_flag,
        'msg': msg
    }
    data_json = json.dumps(data_dict)
    return HttpResponse(data_json)
